package com.example.newsapplication.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

public class FixedViewPager2 extends ViewGroup {
    private ViewPager2 viewPager2;
    public FixedViewPager2(@NonNull Context context) {
        super(context);
        init(context);
    }
    public FixedViewPager2(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public FixedViewPager2(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }
    private void init(Context context) {
        viewPager2 = new ViewPager2(context);
        addView(viewPager2, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    }
    public void setAdapter(RecyclerView.Adapter<?> adapter) {
        viewPager2.setAdapter(adapter);
    }

    public void setCurrentItem(int item) {
        viewPager2.setCurrentItem(item, false); // 禁用平滑滚动
    }

    public void setOffscreenPageLimit(int limit) {
        viewPager2.setOffscreenPageLimit(limit);
    }

    public void registerOnPageChangeCallback(ViewPager2.OnPageChangeCallback callback) {
        viewPager2.registerOnPageChangeCallback(callback);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getDefaultSize(0, widthMeasureSpec);
        int height = getDefaultSize(0, heightMeasureSpec);
        setMeasuredDimension(width, height);

        measureChild(viewPager2, widthMeasureSpec, heightMeasureSpec);
    }
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        viewPager2.layout(0, 0, r - l, b - t);
    }

}
